//
// Created by Administrator on 2021/6/15.
//
/**
 * 第一种模板
 * @param nums
 * @param target
 * @return
 * 初始条件：left = 0, right = length-1
 * 终止：left > right
 * 向左查找：right = mid-1
 * 向右查找：left = mid+1
 */
int binarySearch1(vector<int> &nums, int target) {
    if (nums.size() == 0)
        return -1;

    int left = 0, right = nums.size() - 1;
    while (left <= right) {
        // Prevent (left + right) overflow
        int mid = left + (right - left) / 2;
        if (nums[mid] == target) { return mid; }
        else if (nums[mid] < target) { left = mid + 1; }
        else { right = mid - 1; }
    }

    // End Condition: left > right
    return -1;
}

/**
 * 用于查找需要访问数组中当前索引及其直接右邻居索引的元素或条件。
 * @param nums
 * @param target
 * @return
 * 初始条件：left = 0, right = length
 * 终止：left == right
 * 向左查找：right = mid
 * 向右查找：left = mid+1
 */
int binarySearch2(vector<int> &nums, int target) {
    if (nums.size() == 0)
        return -1;

    int left = 0, right = nums.size();
    while (left < right) {
        // Prevent (left + right) overflow
        int mid = left + (right - left) / 2;
        if (nums[mid] == target) { return mid; }
        else if (nums[mid] < target) { left = mid + 1; }
        else { right = mid; }
    }

    // Post-processing:
    // End Condition: left == right
    if (left != nums.size() && nums[left] == target) return left;
    return -1;
}

/**
 * 用于搜索需要访问当前索引及其在数组中的直接左右邻居索引的元素或条件。
 * @param nums
 * @param target
 * @return
 * 初始条件：left = 0, right = length-1
 * 终止：left + 1 == right
 * 向左查找：right = mid
 * 向右查找：left = mid
 */
int binarySearch3(vector<int> &nums, int target) {
    if (nums.size() == 0)
        return -1;

    int left = 0, right = nums.size() - 1;
    while (left + 1 < right) {
        // Prevent (left + right) overflow
        int mid = left + (right - left) / 2;
        if (nums[mid] == target) {
            return mid;
        } else if (nums[mid] < target) {
            left = mid;
        } else {
            right = mid;
        }
    }

    // Post-processing:
    // End Condition: left + 1 == right
    if (nums[left] == target) return left;
    if (nums[right] == target) return right;
    return -1;
}